<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模拟面试题 - AI智能面试系统</title>
    <link href="/vendors/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="/vendors/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        /* 导航栏样式 - 从 fragments/navbar.html 复制 */
        :root {
            --primary-color: #667eea;
            --secondary-color: #764ba2;
            --accent-color: #f093fb;
            --text-dark: #2d3748;
            --text-light: #718096;
            --bg-light: #f7fafc;
        }

        /* 统一导航栏样式 */
        .unified-navbar {
            background: white !important;
            border-bottom: 1px solid #e5e7eb !important;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            z-index: 1000 !important;
            height: 70px !important;
            width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
        }

        .unified-navbar-container {
            width: 100%;
            padding: 0 24px;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .unified-navbar-left {
            flex-shrink: 0;
        }

        .unified-navbar-brand {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #1f2937;
            font-weight: 700;
            font-size: 1.5rem;
        }

        .unified-navbar-brand i {
            color: var(--primary-color);
            margin-right: 8px;
            font-size: 1.2rem;
        }

        .unified-navbar-brand:hover {
            color: var(--primary-color);
            text-decoration: none;
        }

        .unified-navbar-center {
            flex: 1;
            display: flex;
            justify-content: center;
        }

        .unified-navbar-menu {
            display: flex;
            align-items: center;
            gap: 40px;
        }

        .unified-navbar-right {
            flex-shrink: 0;
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .unified-nav-item {
            display: flex;
            align-items: center;
            text-decoration: none;
            color: #6b7280;
            font-weight: 500;
            font-size: 14px;
            padding: 8px 12px;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .unified-nav-item i {
            margin-right: 6px;
            font-size: 14px;
        }

        .unified-nav-item:hover {
            color: var(--primary-color);
            background: #eff6ff;
            text-decoration: none;
        }

        .unified-nav-item.active {
            color: var(--primary-color);
            background: #eff6ff;
            font-weight: 600;
        }

        /* 用户信息样式 */
        .unified-nav-item.user-info {
            background: #f3f4f6;
            color: var(--primary-color);
            font-weight: 600;
            cursor: default;
        }

        .unified-nav-item.user-info:hover {
            background: #f3f4f6;
            color: var(--primary-color);
        }

        /* 导航栏响应式设计 */
        @media (max-width: 768px) {
            .unified-navbar-container {
                padding: 0 16px;
            }
            
            .unified-navbar-menu {
                gap: 15px;
            }
            
            .unified-nav-item {
                font-size: 13px;
                padding: 6px 8px;
            }
            
            .unified-navbar-brand {
                font-size: 1.3rem;
            }
        }

        @media (max-width: 576px) {
            .unified-navbar-center {
                display: none;
            }
            
            .unified-navbar-right {
                gap: 10px;
            }
        }
        
        /* === 面试页面专用样式 === */
        /* 重置默认样式，但不影响导航栏 */
        .page-container {
            box-sizing: border-box;
        }
        
        .page-container * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            margin: 0;
            padding: 0;
        }
        
        .page-container {
            min-height: calc(100vh - 70px);
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
            padding-top: 90px; /* 为固定导航栏留出足够空间 */
        }
        
        .container {
            width: 1200px;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            animation: fadeInUp 0.8s ease-out;
            display: flex;
            min-height: 600px;
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* 左侧题目选择区域 */
        .sidebar {
            width: 350px;
            background: #f8f9fa;
            border-right: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
        }
        
        .sidebar-header {
            padding: 20px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            text-align: center;
        }
        
        .sidebar-header h2 {
            font-size: 20px;
            margin-bottom: 5px;
        }
        
        .sidebar-header p {
            font-size: 14px;
            opacity: 0.9;
        }
        
        /* 输入表单样式 */
        .input-form {
            padding: 20px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            font-family: inherit;
            transition: all 0.3s ease;
            background: white;
        }
        
        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 60px;
        }
        
        .btn-generate {
            width: 100%;
            padding: 12px 20px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
        }
        
        .btn-generate:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(79, 172, 254, 0.4);
        }
        
        .btn-generate:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .btn-loading {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-loading::after {
            content: '';
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-top: 2px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        /* 欢迎消息样式 */
        .welcome-message {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }
        
        .welcome-icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        
        .welcome-message h3 {
            font-size: 18px;
            margin-bottom: 10px;
            color: #333;
        }
        
        .welcome-message p {
            font-size: 14px;
            line-height: 1.5;
        }
        
        /* 题目列表 */
        .question-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }
        
        .question-item {
            padding: 15px;
            margin-bottom: 8px;
            background: white;
            border-radius: 10px;
            border: 2px solid transparent;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .question-item:hover {
            border-color: #4facfe;
            transform: translateX(5px);
        }
        
        .question-item.active {
            border-color: #4facfe;
            background: linear-gradient(135deg, #4facfe15, #00f2fe15);
        }
        
        .question-item h4 {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
            line-height: 1.4;
        }
        
        .question-item .question-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: #888;
        }
        
        .difficulty {
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: bold;
        }
        
        .difficulty.easy {
            background: #d4edda;
            color: #155724;
        }
        
        .difficulty.medium {
            background: #fff3cd;
            color: #856404;
        }
        
        .difficulty.hard {
            background: #f8d7da;
            color: #721c24;
        }
        
        /* 右侧主要内容区域 */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            padding: 30px;
            text-align: center;
            color: white;
            position: relative;
        }
        
        .header h1 {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        .ai-avatar {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            margin: 0 auto 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 30px;
        }
        
        /* 头部操作按钮 */
        .header-action {
            position: absolute;
            top: 20px;
            right: 20px;
        }
        
        .btn-outline-light {
            background: rgba(255,255,255,0.1);
            color: white;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 25px;
            padding: 8px 16px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-outline-light:hover {
            background: rgba(255,255,255,0.2);
            border-color: rgba(255,255,255,0.5);
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }
        
        .chat-bubble {
            background: rgba(255,255,255,0.15);
            border-radius: 15px;
            padding: 15px;
            margin: 15px 0;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            font-size: 14px;
        }
        
        .content {
            flex: 1;
            padding: 30px;
            overflow-y: auto;
        }
        
        .question-section {
            margin-bottom: 25px;
        }
        
        .question-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
            color: #333;
        }
        
        .question-icon {
            width: 24px;
            height: 24px;
            background: #ff6b6b;
            border-radius: 50%;
            margin-right: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 12px;
        }
        
        .question-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        
        .question-counter {
            margin-left: auto;
            background: #e3f2fd;
            color: #1976d2;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .question-text {
            font-size: 16px;
            color: #555;
            margin-bottom: 20px;
            line-height: 1.8;
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            border-left: 4px solid #4facfe;
        }
        
        .answer-area {
            position: relative;
            margin-bottom: 25px;
        }
        
        .answer-textarea {
            width: 100%;
            min-height: 180px;
            padding: 20px;
            border: 2px solid #e0e0e0;
            border-radius: 15px;
            font-size: 15px;
            font-family: inherit;
            resize: vertical;
            transition: all 0.3s ease;
            background: #fafafa;
        }
        
        .answer-textarea:focus {
            outline: none;
            border-color: #4facfe;
            background: white;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }
        
        .answer-textarea::placeholder {
            color: #999;
            font-style: italic;
        }
        
        .button-group {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 25px;
            gap: 10px;
        }
        
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 25px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-secondary {
            background: #f5f5f5;
            color: #666;
            border: 2px solid #e0e0e0;
        }
        
        .btn-secondary:hover {
            background: #e0e0e0;
            transform: translateY(-2px);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(79, 172, 254, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(86, 171, 47, 0.3);
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(86, 171, 47, 0.4);
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(255, 154, 158, 0.3);
        }
        
        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(255, 154, 158, 0.4);
        }
        
        .progress-bar {
            width: 100%;
            height: 6px;
            background: #e0e0e0;
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 20px;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
            width: 0%;
            transition: width 0.3s ease;
        }
        
        /* 响应式设计 */
        @media (max-width: 1024px) {
            .container {
                width: 95%;
                flex-direction: column;
                min-height: auto;
            }
            
            .sidebar {
                width: 100%;
                max-height: 300px;
            }
            
            .category-tabs {
                flex-wrap: wrap;
            }
            
            .category-tab {
                font-size: 12px;
                padding: 10px 5px;
            }
        }
        
        @media (max-width: 768px) {
            .content {
                padding: 20px;
            }
            
            .header {
                padding: 20px;
            }
            
            .header h1 {
                font-size: 24px;
            }
            
            .button-group {
                flex-direction: column;
                gap: 10px;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
            
            .question-item h4 {
                font-size: 13px;
            }
        }
        
        /* 加载动画 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 40px;
            color: #666;
        }
        
        .loading::after {
            content: '';
            width: 20px;
            height: 20px;
            border: 2px solid #e0e0e0;
            border-top: 2px solid #4facfe;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- 统一导航栏 -->
    <header class="unified-navbar">
        <div class="unified-navbar-container">
            <div class="unified-navbar-left">
                <a href="/" class="unified-navbar-brand">
                    <i class="fas fa-briefcase"></i>
                    <span>AI超级面试官平台</span>
                </a>
            </div>
            
            <div class="unified-navbar-center">
                <nav class="unified-navbar-menu">
                    <a href="/" class="unified-nav-item">首页</a>
                    <a href="/chat" class="unified-nav-item">
                        <i class="fas fa-robot"></i>
                        AI智能助手
                    </a>
                    <a href="/interview" class="unified-nav-item active">
                        <i class="fas fa-clipboard-question"></i>
                        模拟面试题
                    </a>
                    <a href="/job-search" class="unified-nav-item">
                        <i class="fas fa-search"></i>
                        职位搜索
                    </a>
                </nav>
            </div>
            
            <div class="unified-navbar-right" id="navbar-right">
                <!-- 这里的内容将由auth.js动态更新 -->
                <a href="/login" class="unified-nav-item">
                    <i class="fas fa-sign-in-alt"></i>
                    登录
                </a>
                <a href="/register" class="unified-nav-item">
                    <i class="fas fa-user-plus"></i>
                    注册
                </a>
            </div>
        </div>
    </header>
    
    <div class="page-container">
        <div class="container">
        <!-- 左侧题目生成区域 -->
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>🤖 AI面试生成器</h2>
                <p>输入信息生成专属面试题</p>
            </div>
            
            <!-- 输入表单 -->
            <div class="input-form" id="inputForm">
                <div class="form-group">
                    <label>目标岗位</label>
                    <input type="text" id="postInput" placeholder="如：Java后端开发、前端工程师" required>
                </div>
                
                <div class="form-group">
                    <label>工作经验</label>
                    <select id="experienceSelect" required>
                        <option value="">请选择经验</option>
                        <option value="应届生无经验">应届生无经验</option>
                        <option value="1年经验">1年经验</option>
                        <option value="2年经验">2年经验</option>
                        <option value="3年经验">3年经验</option>
                        <option value="4-5年经验">4-5年经验</option>
                        <option value="5年以上经验">5年以上经验</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>技能描述</label>
                    <textarea id="skillInput" placeholder="如：熟悉Spring、MySQL、Redis等技术" rows="3" required></textarea>
                </div>
                
                <button class="btn btn-generate" id="generateBtn">
                    <span class="btn-text">🚀 生成面试题</span>
                    <span class="btn-loading" style="display: none;">生成中...</span>
                </button>
            </div>
            
            <!-- 题目列表 -->
            <div class="question-list" id="questionList">
                <div class="welcome-message">
                    <div class="welcome-icon">💡</div>
                    <h3>欢迎使用AI面试生成器</h3>
                    <p>填写上方表单，即可获得专属的面试题目</p>
                </div>
            </div>
        </div>
        
        <!-- 右侧主要内容区域 -->
        <div class="main-content">
                    <div class="header">
            <div class="ai-avatar">📝</div>
            <h1>模拟面试题</h1>
            <div class="chat-bubble">
                "请认真回答问题，系统会智能分析您的回答质量并提供专业建议"
            </div>
            <!-- 查看记录按钮 -->
            <div class="header-action">
                <button class="btn btn-outline-light" id="viewRecordsBtn">
                    <i class="fas fa-history"></i> 查看记录
                </button>
            </div>
        </div>
            
            <div class="content">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                
                <div class="question-section">
                    <div class="question-header">
                        <div class="question-icon">📝</div>
                        <div class="question-title" id="questionTitle">请选择一个题目开始练习</div>
                        <div class="question-counter" id="questionCounter">等待选择</div>
                    </div>
                    
                    <div class="question-text" id="questionText">
                        请从左侧题目库中选择一个您想要练习的题目，然后开始回答。
                    </div>
                </div>
                
                <div class="answer-area">
                    <textarea class="answer-textarea" id="answerTextarea" placeholder="请在此输入您的答案..." rows="8" disabled></textarea>
                </div>
                
                <div class="button-group">
                    <button class="btn btn-secondary" id="prevBtn" disabled>⬅ 上一题</button>
                    <button class="btn btn-primary" id="nextBtn" disabled>下一题 ➡</button>
                    <button class="btn btn-info" id="saveBtn" disabled>💾 保存本题</button>
                    <button class="btn btn-success" id="submitAllBtn" disabled>📝 提交所有答案</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        // 全局变量
        let currentQuestionIndex = -1;
        let currentQuestions = [];
        let userAnswers = {};
        let isGenerating = false;
        let currentSessionId = null; // 当前面试会话ID
        let answerStartTime = null; // 回答开始时间
        
        // DOM元素
        const questionList = document.getElementById('questionList');
        const questionTitle = document.getElementById('questionTitle');
        const questionText = document.getElementById('questionText');
        const questionCounter = document.getElementById('questionCounter'); 
        const answerTextarea = document.getElementById('answerTextarea');
        const progressFill = document.getElementById('progressFill');
        const prevBtn = document.getElementById('prevBtn');
        const nextBtn = document.getElementById('nextBtn');
        const saveBtn = document.getElementById('saveBtn');
        const submitAllBtn = document.getElementById('submitAllBtn');
        
        // 新增的表单元素
        const postInput = document.getElementById('postInput');
        const experienceSelect = document.getElementById('experienceSelect');
        const skillInput = document.getElementById('skillInput');
        const generateBtn = document.getElementById('generateBtn');
        const btnText = generateBtn.querySelector('.btn-text');
        const btnLoading = generateBtn.querySelector('.btn-loading');
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            setupEventListeners();
            resetInterface();
        });
        
        // 设置事件监听器
        function setupEventListeners() {
            // 生成面试题按钮
            generateBtn.addEventListener('click', generateQuestions);
            
            // 查看记录按钮
            document.getElementById('viewRecordsBtn').addEventListener('click', function() {
                window.location.href = '/interview/records';
            });
            
            // 表单回车键支持
            [postInput, experienceSelect, skillInput].forEach(element => {
                element.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter' && !isGenerating) {
                        generateQuestions();
                    }
                });
            });
            
            // 按钮事件
            prevBtn.addEventListener('click', () => switchQuestion(currentQuestionIndex - 1));
            nextBtn.addEventListener('click', () => switchQuestion(currentQuestionIndex + 1));
            saveBtn.addEventListener('click', saveCurrentAnswer);
            submitAllBtn.addEventListener('click', submitAllAnswers);
            
            // 答案输入事件
            answerTextarea.addEventListener('input', function() {
                const currentQuestion = getCurrentQuestion();
                if (currentQuestion) {
                    userAnswers[currentQuestion.id] = this.value;
                    updateProgress();
                }
            });
            
            // 键盘快捷键
            document.addEventListener('keydown', function(e) {
                if (e.ctrlKey) {
                    switch(e.key) {
                        case 'ArrowLeft': 
                            e.preventDefault();
                            if (!prevBtn.disabled) prevBtn.click();
                            break;
                        case 'ArrowRight':
                            e.preventDefault(); 
                            if (!nextBtn.disabled) nextBtn.click();
                            break;
                        case 'Enter':
                            e.preventDefault();
                            if (!saveBtn.disabled) saveBtn.click();
                            break;
                    }
                }
            });
        }
        
        // 生成面试题目
        async function generateQuestions() {
            // 获取表单数据
            const post = postInput.value.trim();
            const workExperience = experienceSelect.value;
            const skill = skillInput.value.trim();
            
            // 表单验证
            if (!post) {
                alert('请输入目标岗位');
                postInput.focus();
                return;
            }
            
            if (!workExperience) {
                alert('请选择工作经验');
                experienceSelect.focus();
                return;
            }
            
            if (!skill) {
                alert('请输入技能描述');
                skillInput.focus();
                return;
            }
            
            // 设置加载状态
            setGeneratingState(true);
            
            try {
                // 获取token
                const token = localStorage.getItem('token');
                const headers = {
                    'Content-Type': 'application/json'
                };
                if (token) {
                    headers['Authorization'] = 'Bearer ' + token;
                }
                
                // 调用后端API
                const response = await fetch('/interview/generate', {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify({
                        post: post,
                        workExperience: workExperience,
                        skill: skill
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 使用后端返回的会话ID
                    currentSessionId = data.sessionId;
                    
                    // 更新题目列表
                    currentQuestions = data.questions || [];
                    loadGeneratedQuestions();
                    
                    // 显示成功消息
                    showMessage('面试题目生成成功！共生成 ' + currentQuestions.length + ' 道题目', 'success');
                    
                    // 自动选择第一题
                    if (currentQuestions.length > 0) {
                        selectQuestion(0);
                    }
                } else {
                    showMessage(data.message || '生成失败，请稍后重试', 'error');
                }
                
            } catch (error) {
                console.error('生成面试题目失败:', error);
                showMessage('网络错误，请检查网络连接后重试', 'error');
            } finally {
                setGeneratingState(false);
            }
        }
        
        // 设置生成状态
        function setGeneratingState(generating) {
            isGenerating = generating;
            generateBtn.disabled = generating;
            
            if (generating) {
                btnText.style.display = 'none';
                btnLoading.style.display = 'inline-flex';
            } else {
                btnText.style.display = 'inline';
                btnLoading.style.display = 'none';
            }
        }
        
        // 加载生成的题目列表
        function loadGeneratedQuestions() {
            questionList.innerHTML = '';
            
            if (currentQuestions.length === 0) {
                questionList.innerHTML = '<div class="welcome-message"><div class="welcome-icon">😊</div><h3>题目生成完成</h3><p>但没有解析到有效的题目内容</p></div>';
                return;
            }
            
            currentQuestions.forEach((question, index) => {
                const questionItem = document.createElement('div');
                questionItem.className = 'question-item';
                questionItem.dataset.index = index;
                
                const importantIcon = question.isImportant ? '⭐ ' : '';
                
                questionItem.innerHTML = `
                    <h4>${importantIcon}${question.title}</h4>
                    <div class="question-meta">
                        <span>${question.category}</span>
                        <span class="difficulty ${question.difficulty}">${getDifficultyText(question.difficulty)}</span>
                    </div>
                `;
                
                questionItem.addEventListener('click', () => selectQuestion(index));
                questionList.appendChild(questionItem);
            });
        }
        
        // 显示消息
        function showMessage(message, type = 'info') {
            // 可以在这里添加更好的消息显示组件
            if (type === 'error') {
                alert('❌ ' + message);
            } else if (type === 'success') {
                // 临时显示成功消息，可以后续改为更好的UI
                console.log('✅ ' + message);
            }
        }
        
        // 选择题目
        function selectQuestion(index) {
            if (index < 0 || index >= currentQuestions.length) return;
            
            currentQuestionIndex = index;
            const question = currentQuestions[index];
            
            // 更新界面
            updateQuestionDisplay(question);
            updateQuestionListStyle();
            updateButtonStates();
            updateProgress();
            
            // 恢复之前的答案
            answerTextarea.value = userAnswers[question.id] || '';
            answerTextarea.disabled = false;
            
            // 记录回答开始时间
            answerStartTime = Date.now();
        }
        
        // 更新题目显示
        function updateQuestionDisplay(question) {
            questionTitle.textContent = question.title;
            questionText.textContent = question.content;
            questionCounter.textContent = `第 ${currentQuestionIndex + 1}/${currentQuestions.length} 题`;
        }
        
        // 更新题目列表样式
        function updateQuestionListStyle() {
            document.querySelectorAll('.question-item').forEach((item, index) => {
                item.classList.remove('active');
                if (index === currentQuestionIndex) {
                    item.classList.add('active');
                }
            });
        }
        
        // 更新按钮状态
        function updateButtonStates() {
            prevBtn.disabled = currentQuestionIndex <= 0;
            nextBtn.disabled = currentQuestionIndex >= currentQuestions.length - 1;
            saveBtn.disabled = currentQuestionIndex === -1;
            submitAllBtn.disabled = currentQuestions.length === 0;
        }
        
        // 切换题目
        function switchQuestion(newIndex) {
            if (newIndex >= 0 && newIndex < currentQuestions.length) {
                selectQuestion(newIndex);
            }
        }
        

        
        // 保存当前题目答案
        async function saveCurrentAnswer() {
            const currentQuestion = getCurrentQuestion();
            if (!currentQuestion) return;
            
            const answer = answerTextarea.value.trim();
            if (!answer) {
                alert('请先输入答案再保存！');
                return;
            }
            
            // 计算回答时长
            const answerDuration = answerStartTime ? Math.floor((Date.now() - answerStartTime) / 1000) : null;
            
            // 保存答案到本地内存
            userAnswers[currentQuestion.id] = answer;
            
            // 尝试保存到数据库（仅登录用户）
            const token = localStorage.getItem('token');
            if (token && currentSessionId) {
                try {
                    await saveAnswerToDatabase(currentQuestion, answer, answerDuration);
                    showSaveSuccess();
                } catch (error) {
                    console.log('保存到数据库失败（可能未登录）:', error);
                    showSaveSuccess(); // 本地保存仍然成功
                }
            } else {
                showSaveSuccess();
            }
            
            // 更新进度
            updateProgress();
        }
        
        // 提交所有答案
        async function submitAllAnswers() {
            // 检查是否有题目
            if (currentQuestions.length === 0) {
                alert('请先生成面试题目！');
                return;
            }
            
            // 检查是否有已回答的题目
            const answeredCount = Object.keys(userAnswers).length;
            if (answeredCount === 0) {
                alert('请至少回答一道题目再提交！');
                return;
            }
            
            // 确认提交
            const totalCount = currentQuestions.length;
            const confirmMessage = `您已回答 ${answeredCount}/${totalCount} 道题目。\n\n是否确认提交所有答案？提交后将无法修改。`;
            
            if (!confirm(confirmMessage)) {
                return;
            }
            
            // 显示提交中状态
            const originalText = submitAllBtn.textContent;
            submitAllBtn.textContent = '📤 提交中...';
            submitAllBtn.disabled = true;
            
            try {
                // 如果当前题目有未保存的答案，先保存
                const currentQuestion = getCurrentQuestion();
                if (currentQuestion && answerTextarea.value.trim()) {
                    userAnswers[currentQuestion.id] = answerTextarea.value.trim();
                }
                
                // 批量提交所有答案到数据库
                const token = localStorage.getItem('token');
                if (token && currentSessionId) {
                    try {
                        const result = await submitAllAnswersToDatabase();
                        showSubmissionComplete(answeredCount, result.savedCount);
                    } catch (error) {
                        console.error('批量提交失败:', error);
                        showSubmissionComplete(answeredCount, 0);
                    }
                } else {
                    // 未登录用户的提交处理
                    showSubmissionComplete(answeredCount, 0);
                }
                
            } catch (error) {
                console.error('提交所有答案失败:', error);
                alert('提交失败，请稍后重试！');
            } finally {
                // 恢复按钮状态
                submitAllBtn.textContent = originalText;
                submitAllBtn.disabled = false;
            }
        }
        
        // 保存答案到数据库
        async function saveAnswerToDatabase(question, answerContent, answerDuration) {
            const token = localStorage.getItem('token');
            if (!token) {
                throw new Error('未登录');
            }
            
            const requestData = {
                sessionId: currentSessionId,
                questionId: question.id,
                questionTitle: question.title,
                questionContent: question.content,
                questionCategory: question.category,
                answerContent: answerContent,
                answerDuration: answerDuration
            };
            
            const response = await fetch('/interview/saveAnswer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token
                },
                body: JSON.stringify(requestData)
            });
            
            const data = await response.json();
            
            if (!data.success) {
                console.error('保存答案失败:', data.message);
                throw new Error(data.message);
            }
            
            console.log('答案保存成功:', data.message);
            return data;
        }
        
        // 批量提交所有答案到数据库
        async function submitAllAnswersToDatabase() {
            const token = localStorage.getItem('token');
            if (!token) {
                throw new Error('未登录');
            }
            
            // 构建答案数组，包括所有题目（不管是否有答案）
            const answers = [];
            for (const question of currentQuestions) {
                const answerContent = userAnswers[question.id] || ''; // 未回答的题目答案为空字符串
                answers.push({
                    questionId: question.id,
                    questionTitle: question.title,
                    questionContent: question.content,
                    questionCategory: question.category,
                    answerContent: answerContent,
                    answerDuration: null // 批量提交时不记录单题时长
                });
            }
            
            const requestData = {
                sessionId: currentSessionId,
                answers: answers,
                targetPosition: postInput.value.trim(),
                workExperience: experienceSelect.value,
                skills: skillInput.value.trim()
            };
            
            const response = await fetch('/interview/submitAll', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer ' + token
                },
                body: JSON.stringify(requestData)
            });
            
            const data = await response.json();
            
            if (!data.success) {
                console.error('批量提交失败:', data.message);
                throw new Error(data.message);
            }
            
            console.log('批量提交成功:', data.message);
            return data;
        }
        
        // 显示保存成功消息
        function showSaveSuccess() {
            const originalText = saveBtn.textContent;
            const originalBg = saveBtn.style.background;
            
            saveBtn.textContent = '✅ 已保存';
            saveBtn.style.background = 'linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%)';
            
            setTimeout(() => {
                saveBtn.textContent = originalText;
                saveBtn.style.background = originalBg;
            }, 1500);
        }
        
        // 显示提交完成消息
        function showSubmissionComplete(answeredCount, savedCount) {
            const token = localStorage.getItem('token');
            let message = `面试完成！\n\n`;
            message += `📊 统计信息：\n`;
            message += `- 已回答题目：${answeredCount} 道\n`;
            message += `- 总题目数：${currentQuestions.length} 道\n`;
            
            if (token) {
                message += `- 成功保存：${savedCount} 道\n\n`;
                if (savedCount > 0) {
                    message += `✅ 您的面试答案已保存到数据库，可在个人中心查看历史记录。`;
                } else {
                    message += `⚠️ 数据库保存失败，但本地已记录您的答案。`;
                }
            } else {
                message += `\n💡 提示：登录后您的答案将自动保存，方便后续查看和分析。`;
            }
            
            if (confirm(message + '\n\n是否立即查看详细分析报告？')) {
                // 跳转到结果分析页面
                window.location.href = '/interview/analysis?sessionId=' + currentSessionId;
            }
        }
        

        
        // 更新进度条
        function updateProgress() {
            const totalQuestions = currentQuestions.length;
            const answeredQuestions = currentQuestions.filter(q => userAnswers[q.id]).length;
            const progress = totalQuestions > 0 ? (answeredQuestions / totalQuestions) * 100 : 0;
            
            progressFill.style.width = progress + '%';
        }
        
        // 获取当前题目
        function getCurrentQuestion() {
            return currentQuestionIndex >= 0 ? currentQuestions[currentQuestionIndex] : null;
        }
        
        // 重置界面
        function resetInterface() {
            questionTitle.textContent = '🚀 准备开始AI面试';
            questionText.textContent = '请在左侧填写您的岗位信息，点击"生成面试题"按钮，AI将为您量身定制专业的面试题目。';
            questionCounter.textContent = '等待生成';
            answerTextarea.value = '';
            answerTextarea.disabled = true;
            updateButtonStates();
            progressFill.style.width = '0%';
            currentQuestionIndex = -1;
            currentQuestions = [];
            userAnswers = {};
            currentSessionId = null;
            answerStartTime = null;
        }
        
        // 获取难度文本
        function getDifficultyText(difficulty) {
            const difficultyMap = {
                'easy': '简单',
                'medium': '中等', 
                'hard': '困难'
            };
            return difficultyMap[difficulty] || '未知';
        }
        
        // 按钮点击效果
        document.querySelectorAll('.btn').forEach(btn => {
            btn.addEventListener('click', function() {
                if (!this.disabled) {
                    this.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        this.style.transform = '';
                    }, 150);
                }
            });
        });
    </script>
    </div> <!-- 关闭 page-container -->
    
    <!-- 认证管理脚本 -->
    <script src="/js/auth.js"></script>
</body>
</html>